<template>
  <div class="activity-statistics">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>活动统计</h1>
      <p>活动数据统计与分析</p>
    </div>

    <!-- 时间筛选 -->
    <el-card shadow="never" class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="统计时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refreshStatistics" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新统计
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 概览统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ statistics.overview?.total_activities || 0 }}</h3>
              <p>总活动数</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon active">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ statistics.overview?.open_activities || 0 }}</h3>
              <p>进行中活动</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon completed">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ statistics.overview?.closed_activities || 0 }}</h3>
              <p>已结束活动</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon participants">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ statistics.overview?.total_participants || 0 }}</h3>
              <p>总参与人次</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表统计 -->
    <el-row :gutter="20" class="chart-section">
      <!-- 月度活动趋势 -->
      <el-col :span="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <span class="chart-title">月度活动趋势</span>
          </template>
          <div ref="monthlyChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 活动状态分布 -->
      <el-col :span="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <span class="chart-title">活动状态分布</span>
          </template>
          <div ref="statusChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 场馆使用统计 -->
    <el-card shadow="never" class="venue-stats-card">
      <template #header>
        <span class="chart-title">场馆使用统计 (Top 10)</span>
      </template>
      
      <el-table :data="statistics.venue_stats" style="width: 100%">
        <el-table-column prop="venue_name" label="场馆名称" min-width="200" />
        <el-table-column prop="activity_count" label="活动数量" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="primary">{{ row.activity_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="使用频率" width="200">
          <template #default="{ row }">
            <el-progress 
              :percentage="getVenueUsagePercentage(row.activity_count)"
              :stroke-width="12"
              :show-text="false"
            />
            <span class="percentage-text">{{ getVenueUsagePercentage(row.activity_count) }}%</span>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="!statistics.venue_stats?.length" class="empty-data">
        <el-empty description="暂无场馆使用数据" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Calendar, Check, CircleCheck, User, Refresh } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import request from '@/utils/request'

export default {
  name: 'ActivityStatistics',
  components: {
    Calendar, Check, CircleCheck, User, Refresh
  },
  setup() {
    const loading = ref(false)
    const monthlyChartRef = ref(null)
    const statusChartRef = ref(null)
    
    let monthlyChart = null
    let statusChart = null

    // 筛选表单
    const filterForm = reactive({
      dateRange: [],
      start_date: '',
      end_date: ''
    })

    // 统计数据
    const statistics = reactive({
      overview: {
        total_activities: 0,
        open_activities: 0,
        closed_activities: 0,
        cancelled_activities: 0,
        total_participants: 0
      },
      monthly_stats: [],
      venue_stats: []
    })

    // 处理日期变化
    const handleDateChange = (val) => {
      if (val && val.length === 2) {
        filterForm.start_date = val[0]
        filterForm.end_date = val[1]
      } else {
        filterForm.start_date = ''
        filterForm.end_date = ''
      }
    }

    // 获取统计数据
    const fetchStatistics = async () => {
      loading.value = true
      try {
        const params = {
          start_date: filterForm.start_date,
          end_date: filterForm.end_date
        }
        
        const response = await request.get('/v1/admin/activities/statistics', { params })
        
        if (response.code === 200) {
          Object.assign(statistics, response.data)
          
          // 更新图表
          await nextTick()
          updateCharts()
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        ElMessage.error('获取统计数据失败')
      } finally {
        loading.value = false
      }
    }

    // 刷新统计
    const refreshStatistics = () => {
      fetchStatistics()
    }

    // 更新图表
    const updateCharts = () => {
      updateMonthlyChart()
      updateStatusChart()
    }

    // 更新月度趋势图表
    const updateMonthlyChart = () => {
      if (!monthlyChart) {
        monthlyChart = echarts.init(monthlyChartRef.value)
      }

      const months = statistics.monthly_stats?.map(item => item.month) || []
      const counts = statistics.monthly_stats?.map(item => item.count) || []

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: months,
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '活动数量',
            type: 'bar',
            barWidth: '60%',
            data: counts,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#409eff' },
                { offset: 1, color: '#79bbff' }
              ])
            }
          }
        ]
      }

      monthlyChart.setOption(option)
    }

    // 更新状态分布图表
    const updateStatusChart = () => {
      if (!statusChart) {
        statusChart = echarts.init(statusChartRef.value)
      }

      const data = [
        { value: statistics.overview?.open_activities || 0, name: '进行中', itemStyle: { color: '#67c23a' } },
        { value: statistics.overview?.closed_activities || 0, name: '已结束', itemStyle: { color: '#909399' } },
        { value: statistics.overview?.cancelled_activities || 0, name: '已取消', itemStyle: { color: '#f56c6c' } }
      ]

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '活动状态',
            type: 'pie',
            radius: '50%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }

      statusChart.setOption(option)
    }

    // 计算场馆使用百分比
    const getVenueUsagePercentage = (count) => {
      const maxCount = Math.max(...(statistics.venue_stats?.map(item => item.activity_count) || [0]))
      return maxCount > 0 ? Math.round((count / maxCount) * 100) : 0
    }

    // 初始化图表
    const initCharts = async () => {
      await nextTick()
      
      if (monthlyChartRef.value) {
        monthlyChart = echarts.init(monthlyChartRef.value)
      }
      
      if (statusChartRef.value) {
        statusChart = echarts.init(statusChartRef.value)
      }

      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        monthlyChart?.resize()
        statusChart?.resize()
      })
    }

    // 组件卸载时清理
    const cleanup = () => {
      monthlyChart?.dispose()
      statusChart?.dispose()
      window.removeEventListener('resize', () => {
        monthlyChart?.resize()
        statusChart?.resize()
      })
    }

    onMounted(async () => {
      await initCharts()
      fetchStatistics()
    })

    return {
      loading,
      monthlyChartRef,
      statusChartRef,
      filterForm,
      statistics,
      handleDateChange,
      refreshStatistics,
      getVenueUsagePercentage
    }
  },
  beforeUnmount() {
    // 清理图表实例
    this.cleanup?.()
  }
}
</script>

<style scoped>
.activity-statistics {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.page-header p {
  margin: 5px 0 0 0;
  color: #606266;
}

.filter-card {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.stat-icon.completed {
  background: linear-gradient(135deg, #909399 0%, #c0c4cc 100%);
}

.stat-icon.participants {
  background: linear-gradient(135deg, #409eff 0%, #79bbff 100%);
}

.stat-info {
  text-align: right;
}

.stat-info h3 {
  margin: 0;
  font-size: 28px;
  color: #303133;
  font-weight: bold;
}

.stat-info p {
  margin: 5px 0 0 0;
  color: #606266;
  font-size: 14px;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.venue-stats-card .percentage-text {
  margin-left: 10px;
  color: #606266;
  font-size: 12px;
}

.empty-data {
  text-align: center;
  padding: 40px 0;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table) {
  font-size: 14px;
}
</style> 